package com.luoyulin.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luoyulin.reggie.common.CustomExeception;
import com.luoyulin.reggie.dto.SetmealDto;
import com.luoyulin.reggie.entity.Setmeal;
import com.luoyulin.reggie.entity.SetmealDish;
import com.luoyulin.reggie.mapper.SetMealMapper;
import com.luoyulin.reggie.service.SetmealDishService;
import com.luoyulin.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.object.UpdatableSqlQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author luoyulin
 * @create 2022-04-24 12:51
 **/
@Service
public class SetmealServiceImpl extends ServiceImpl<SetMealMapper,Setmeal> implements SetmealService{

    @Autowired
    private SetmealDishService setmealDishService;
    /**
     * 新增套餐
     * @param setmealDto
     */
    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存基本信息,setmeal表
        this.save(setmealDto);
        //保存关联表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) ->{
           item.setSetmealId(setmealDto.getId());
           return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }

    @Transactional
    @Override
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);

        int count = this.count(queryWrapper);
        //如果不能删除
        if(count > 0){
            throw new CustomExeception("套餐售卖中");
        }
        //如果可以删除
        this.removeByIds(ids);
        //删除关系表
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper);
    }
}
